package month5.day6;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class FileServer {
    //定义固定线程数量
    private final static int THREAD_NUMBERS = 32;
    //通过线程池创建线程
    private final static Executor serverTaskHandler = Executors.newFixedThreadPool(THREAD_NUMBERS);
    //windows操作系统文件位置
    private static final String WINDOWS_SAVE_PATH = "D:/files";
    //Linux操作系统文件位置
    private static final String LINUX_SAVE_PATH = "/files/";

    private static String getFileSaverPath(){
        String key="os.name";
        String osName=System.getProperty(key);
        if(osName.contains("WINDOWS")){
            return WINDOWS_SAVE_PATH;
        } else {
            return LINUX_SAVE_PATH;
        }
    }


    public static void main(String[] args) {
        //申明服务器套接字
        ServerSocket filesever = null;
        try {
            //创建服务器套接字对象，并监听9090端口
            filesever = new ServerSocket(9090);
            System.out.println("文件储存服务器已启动...");
            //等待客户端请求到来。并返回客户端对象
            Socket  fileclient = filesever.accept();//accept()方法阻塞方法，一直等待客户端请求到来，才放行
            //获取远程客户端端口
            int port = fileclient.getPort();
            InetAddress ia = fileclient.getInetAddress();
            //获取远程客户端IP
            String ip = ia.getHostAddress();
            System.out.printf("%s客户端成功与服务器链接，端口是:%d%n", ip, port);
            //使用线程池执行提交任务
            serverTaskHandler.execute(()->{
                for(;;){
                    //创建数据输入流
                    DataInputStream dis=null;
                    DataOutputStream dos=null;
                    try {
                        dis=new DataInputStream(fileclient.getInputStream());
                        String fileNmae=dis.readUTF();
                        //创建文件对象
                        File file=new File(getFileSaverPath(),fileNmae);
                        if(!file.exists())
                            file.getParentFile().mkdir();//创建保存文件目录结构

                        //读取客户端发送过来的上传文件名
                        String fileName= dis.readUTF();
                        System.out.println(ip+":"+port+"客户端上传的文件名称是："+fileName);
                        dos=new DataOutputStream(new FileOutputStream(getFileSaverPath()));
                        byte[]buffer=new byte[1024];//创建缓冲区
                        int readBytes=0;//每次实际读取的字节数
                        while ((readBytes=dis.read(buffer))!=-1){
                            dos.write(buffer,0,readBytes);//强制刷新缓冲区
                            dos.flush();

                        }

                    } catch (Exception e) {
                        if(fileclient!=null&&!fileclient.isClosed()){
                            System.out.println(ip+":"+port+"客户端以与服务器断开连接！");
                            try {
                                fileclient.close();
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    }
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
